package com.example.workmanager

import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf

/**
 * Worker:应用程序被强退之后（进程被杀死），后台任务是无法被继续调度的
 * 只有等应用程序再次启动的时候
 * 后台任务才能继续
 */
class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    //需要完成的后台任务
    override fun doWork(): Result {
        //后台获取前台传递过来的数据
        val name = inputData.getString(INPUT_DATA_KEY)
        //Log.d("hello","doWork:$name started")
        Thread.sleep(3000)

        //创建缓存
        val sp = applicationContext.getSharedPreferences(SHARED_PREFERENCEES_NAME,Context.MODE_PRIVATE)

        var number = sp.getInt(name,0)

        sp.edit().putInt(name,++number).apply()

        //Log.d("hello","doWork:$name finished")
        //后台向前台传递数据
        return Result.success(workDataOf(OUTPUT_DATA_KEY to "$name output"))
    }
}